import React, { memo } from "react"
import * as  echarts from 'echarts';

interface AutoChartProps {
    option: echarts.EChartsOption,
    styles?: object
}

const ViewAutoChart: React.FC<AutoChartProps> = (props) => {
    const chartRef = React.useRef(null);
    const [chart, setChart] = React.useState<echarts.ECharts>();
    const handleResize = () => chart?.resize();

    const init = () => {
        if (chart) {
            // 建议替换为 ResizeObserver （2023.5.25）
            window.removeEventListener('resize', handleResize);
        }
        const _chart = echarts.init(chartRef.current as any as HTMLElement);
        _chart.setOption(props.option);
        window.addEventListener('resize', handleResize);
        setChart(_chart);
    };

    React.useEffect(() => {
        init();
        return () =>  window.removeEventListener('resize', handleResize);
    }, [props.option]);

    const styles = props.styles ? props.styles : { height: '100%', width: '100%' }

    return <div ref={chartRef} style={styles} />;
};




export default memo(ViewAutoChart);